package com.ca.ridersclubapplication.service;

import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

import com.ca.ridersclubapplication.data.DataHandler;
import com.ca.ridersclubapplication.data.entity.ListEntity;
import com.ca.ridersclubapplication.request.AfterExecutor;
import com.ca.ridersclubapplication.request.MessageRequester;
import com.ca.ridersclubapplication.request.dto.ChatMessageDto;
import com.ca.ridersclubapplication.request.dto.Result;
import com.ca.ridersclubapplication.util.Logger;

import java.util.List;

public class ChatService extends Service {

    private Intent intent;
    private final Logger log = Logger.getInstance("ChatService");

    private Handler getListHandler;
    private Runnable getListRunnable;
    public static Activity activity;

    public static Long targetId = 0L;
    public static Long endId = 0L;

    private final Object o = new Object();

    @Override
    public void onCreate() {

        getListHandler = new Handler();

        getListRunnable = () -> {


            if (!DataHandler.isLogin(activity)) {
                getListHandler.removeCallbacks(getListRunnable);
                return;
            }

            MessageRequester.setRead(activity, targetId, null);

            synchronized (o) {
                MessageRequester.listNewMsg(activity, targetId, endId, new AfterExecutor<List<ChatMessageDto>>() {
                    @Override
                    public void execute(Result<List<ChatMessageDto>> result) {
                        List<ChatMessageDto> data = result.getData();
                        if (result.isSuccess() && data != null) {
                            DataHandler.putData(new ListEntity<>("HasNewMsg:" + targetId, data));
                            if (data.size() > 0) {
                                endId = data.get(0).getId();
                                Log.e("ChatService", "data.size() = " + data.size() + ", endId = " + endId);
                            }
                            getListHandler.postDelayed(getListRunnable, 500);
                        }
                    }
                });
            }
        };
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        this.intent = intent;
        getListHandler.post(getListRunnable);

        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        getListHandler.removeCallbacks(getListRunnable);
        log.e("停止ChatService");
    }
}